package com.example.demo.demos.aop;

import com.example.demo.demos.annotation.WebLog;
import com.example.demo.demos.utils.RequestUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

@Component
@Aspect
public class myAOP {

    @Resource
    RequestUtil requestUtil;

    //相同切入点抽取
    @Pointcut(value = "execution(* com.example.demo.demos.web.BasicController.*(..))&&@annotation(com.example.demo.demos.annotation.WebLog)")
    public void pointdemo(){}

    @Before(value ="pointdemo()")
    public void before(JoinPoint joinPoint){
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        WebLog annotation = method.getAnnotation(WebLog.class);
        if (ObjectUtils.isEmpty(annotation)) {
            return;
        }
        Parameter[] parameters = method.getParameters();
        String requestOption;
        Object[] args = joinPoint.getArgs();
        for (Parameter parameter : parameters) {
            String name = parameter.getName();
        }
        String value = annotation.value();
        HttpServletRequest request = requestUtil.getRequest();
        HttpSession session = request.getSession();
        Object optionalPerson = session.getAttribute("操作人");
        String url = request.getRequestURL().toString();
        String remoteAddr = request.getRemoteAddr();
        String remoteHost = request.getRemoteHost();
        int remotePort = request.getRemotePort();

        System.out.println("操作人："+optionalPerson);
        System.out.println("操作地址："+url);
        System.out.println("操作："+value);
        System.out.println("操作人地址："+remoteAddr);
    }

    @Before(value ="pointdemo()")
    public void beforeMySql(JoinPoint joinPoint){
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        String name = method.getName();
    }

    @Pointcut(value = "@annotation(org.springframework.stereotype.Controller)")
    public void testAop(){}


    @Before(value = "testAop()")
    public void beforeAop(){

    }
}
